﻿
Imports osi.root.connector

Public MustInherit Class randomAccessIterator(Of T)
    Inherits pointer(Of T)
    Implements container(Of T).iterator

    Protected Function multiTraversal(ByVal steps As Int64, ByVal prev As Boolean) As Boolean
        k_assert(steps > 0, "steps should not less than or equal to 0 in multiTraversal.")

        Dim i As Int64
        For i = 0 To steps - 1
            If Not traversal(prev) Then
                Exit For
            End If
        Next

        Return i = steps
    End Function

    Protected MustOverride Function traversal(ByVal prev As Boolean) As Boolean

    Protected Function [next](ByVal steps As Int64) As Boolean
        If steps > 0 Then
            Return multiTraversal(steps, False)
        ElseIf steps < 0 Then
            Return multiTraversal(-steps, True)
        Else
            Return True
        End If
    End Function

    Public Shared Operator +(ByVal this As randomAccessIterator(Of T), _
                             ByVal that As Int64) As randomAccessIterator(Of T)
        If Not this Is Nothing Then
            this.next(that)
            Return this
        Else
            Return Nothing
        End If
    End Operator

    Public Shared Operator -(ByVal this As randomAccessIterator(Of T), _
                             ByVal that As Int64) As randomAccessIterator(Of T)
        Return this + (-that)
    End Operator

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal that As pointer(Of T))
        MyBase.New(that)
    End Sub

    Public Sub New(ByVal that As T)
        MyBase.New(that)
    End Sub

    Public Overloads Function instance() As T Implements container(Of T).iterator.instance
        Return MyBase.get()
    End Function
End Class

Public Class staticIterator(Of T)
    Inherits pointer(Of T)
    Implements container(Of T).iterator

    Public Sub New()
        MyBase.New()
    End Sub

    Public Sub New(ByVal that As pointer(Of T))
        MyBase.New(that)
    End Sub

    Public Sub New(ByVal that As T)
        MyBase.New(that)
    End Sub

    Public Overloads Function instance() As T Implements container(Of T).iterator.instance
        Return MyBase.get()
    End Function
End Class
